<template>
  <div class="lhx-chat-window">
    <!-- 聊天头部 -->
    <div class="lhx-chat-header">
      <button @click="lhxGoBack" class="lhx-back-btn">←</button>
      <div class="lhx-chat-title">
        <h3>聊天窗口页面</h3>
        <p class="lhx-chat-with">
          {{ lhxIsPatient ? `与 ${lhxOtherUserName} 医生聊天` : `与 ${lhxOtherUserName} 患者聊天` }}
        </p>
      </div>
    </div>
    

    
    <!-- 消息列表：固定最小高度减少CLS -->
    <div class="lhx-messages" ref="lhxMessagesContainer" @scroll="lhxHandleScroll">
      <!-- Skeleton Screen：仅在未连接时显示 -->
      <div v-if="!lhxSocketConnected && !lhxPagination.initialLoaded" class="lhx-skeleton-container">
        <div v-for="i in 3" :key="`skeleton-${i}`" class="lhx-skeleton-message">
          <div class="lhx-skeleton-avatar"></div>
          <div class="lhx-skeleton-content">
            <div class="lhx-skeleton-text short"></div>
            <div class="lhx-skeleton-text long"></div>
          </div>
        </div>
      </div>
      
      <!-- 分页加载提示：仅在启用分页时显示 -->
      <div v-if="lhxShouldUsePagination && lhxPagination.loading && lhxPagination.currentPage > 1" 
           class="lhx-loading-more-simple">
        ···
      </div>
      
      <!-- 空状态：连接后无消息时显示 -->
      <div v-if="lhxSocketConnected && lhxMessages.length === 0 && lhxPagination.initialLoaded" 
           class="lhx-empty-messages">
        <p>暂无聊天记录</p>
        <small>开始您的第一条对话吧</small>
      </div>
      
      <div 
        v-for="message in lhxMessages" 
        :key="message._id || message.timestamp"
        :class="['lhx-message', message.senderId === lhxCurrentUser.userId ? 'lhx-self' : 'lhx-other']"
      >
        <!-- 对方消息布局 -->
        <template v-if="message.senderId !== lhxCurrentUser.userId">
          <div class="lhx-message-avatar">
            <img :src="lhxGetAvatarUrl(message.senderId)" :alt="message.senderType" />
          </div>
          
          <div class="lhx-message-content">
            <div class="lhx-message-bubble">
              <!-- LHX聊天模块 - 文本消息 -->
              <div v-if="message.messageType === 'text'">
                {{ message.content }}
              </div>
              <!-- LHX聊天模块 - 图片消息 -->
              <div v-else-if="message.messageType === 'image'" class="lhx-image-message">
                <img 
                  :src="message.fileInfo?.fileUrl || message.imageUrl" 
                  :alt="message.content || '图片'" 
                  @click="lhxPreviewImage(message.fileInfo?.fileUrl || message.imageUrl)"
                  @load="lhxScrollToBottom"
                  @error="lhxImageError"
                />
              </div>
              <!-- LHX聊天模块 - 语音消息 -->
              <div v-else-if="message.messageType === 'voice'" class="lhx-voice-message">
                <button 
                  @click="lhxPlayVoice(message.fileInfo?.fileUrl, message._id)"
                  :class="['lhx-voice-play-btn', { 'lhx-playing': lhxVoicePlayer.currentPlaying === message._id }]"
                >
                  {{ lhxVoicePlayer.currentPlaying === message._id ? '⏸️' : '▶️' }}
                </button>
                <span class="lhx-voice-duration">{{ message.fileInfo?.duration || 0 }}"</span>
              </div>
            </div>
            <div class="lhx-message-time">
              {{ lhxFormatMessageTime(message.timestamp) }}
            </div>
          </div>
        </template>
        
        <!-- 自己消息布局 -->
        <template v-else>
          <div class="lhx-message-content">
            <div class="lhx-message-bubble">
              <!-- LHX聊天模块 - 文本消息 -->
              <div v-if="message.messageType === 'text'">
                {{ message.content }}
              </div>
              <!-- LHX聊天模块 - 图片消息 -->
              <div v-else-if="message.messageType === 'image'" class="lhx-image-message">
                <img 
                  :src="message.fileInfo?.fileUrl || message.imageUrl" 
                  :alt="message.content || '图片'" 
                  @click="lhxPreviewImage(message.fileInfo?.fileUrl || message.imageUrl)"
                  @load="lhxScrollToBottom"
                  @error="lhxImageError"
                />
              </div>
              <!-- LHX聊天模块 - 语音消息 -->
              <div v-else-if="message.messageType === 'voice'" class="lhx-voice-message">
                <button 
                  @click="lhxPlayVoice(message.fileInfo?.fileUrl, message._id)"
                  :class="['lhx-voice-play-btn', { 'lhx-playing': lhxVoicePlayer.currentPlaying === message._id }]"
                >
                  {{ lhxVoicePlayer.currentPlaying === message._id ? '⏸️' : '▶️' }}
                </button>
                <span class="lhx-voice-duration">{{ message.fileInfo?.duration || 0 }}"</span>
              </div>
            </div>
            <div class="lhx-message-time">
              {{ lhxFormatMessageTime(message.timestamp) }}
            </div>
          </div>
          
          <div class="lhx-message-avatar">
            <img :src="lhxGetAvatarUrl(message.senderId)" :alt="message.senderType" />
          </div>
        </template>
      </div>
      

    </div>
    
    <!-- LHX聊天模块 - 图片放大显示组件 -->
    <div v-if="lhxImagePreview.show" class="lhx-image-preview-overlay" @click="lhxCloseImagePreview">
      <div class="lhx-image-preview-container" @click.stop>
        <div class="lhx-image-preview-header">
          <button @click="lhxCloseImagePreview" class="lhx-image-preview-close">×</button>
          <button @click="lhxDownloadImage" class="lhx-image-preview-download">下载</button>
        </div>
        <div class="lhx-image-preview-content">
          <img 
            :src="lhxImagePreview.url" 
            :alt="lhxImagePreview.alt"
            @load="lhxImagePreviewLoaded"
            @error="lhxImagePreviewError"
          />
        </div>
      </div>
    </div>
    
    <!-- LHX聊天模块 - 通话弹窗 -->
    <div v-if="lhxTrtcCall.isInCall || lhxTrtcCall.isIncoming" class="lhx-call-overlay">
      <div class="lhx-call-container">
        <!-- 来电界面 -->
        <div v-if="lhxTrtcCall.isIncoming" class="lhx-incoming-call">
          <div class="lhx-call-info">
            <h3>{{ lhxTrtcCall.callType === 'video' ? '视频通话' : '语音通话' }}</h3>
            <p>{{ lhxOtherUserName }} 邀请您通话</p>
          </div>
          <div class="lhx-call-actions">
            <button @click="lhxAcceptCall" class="lhx-accept-btn">接听</button>
            <button @click="lhxRejectCall" class="lhx-reject-btn">拒绝</button>
          </div>
        </div>
        
        <!-- 通话中界面 -->
        <div v-else class="lhx-in-call">
          <div class="lhx-call-info">
            <h3>{{ lhxTrtcCall.callType === 'video' ? '视频通话中' : '语音通话中' }}</h3>
            <p>与 {{ lhxOtherUserName }} 通话中</p>
          </div>
          
          <!-- 视频通话时显示视频窗口 -->
          <div v-if="lhxTrtcCall.callType === 'video'" class="lhx-video-container">
            <div id="lhx-remote-video" class="lhx-remote-video"></div>
            <div id="lhx-local-video" class="lhx-local-video"></div>
          </div>
          
          <!-- LHX聊天模块 - 语音通话时的音频播放容器 -->
          <div v-if="lhxTrtcCall.callType === 'audio'" class="lhx-audio-container">
            <div class="lhx-audio-info">
              <div class="lhx-audio-icon">🔊</div>
              <p>语音通话中...</p>
            </div>
          </div>
          
          <!-- LHX聊天模块 - 音频播放容器（隐藏，TRTC会自动创建audio元素） -->
          <div id="lhx-remote-audio" style="display: none;"></div>
          <div id="lhx-local-audio" style="display: none;"></div>
          
          <div class="lhx-call-controls">
            <button @click="lhxToggleMute" class="lhx-control-btn">🔇</button>
            <button @click="lhxEndCall" class="lhx-end-call-btn">📵</button>
            <button v-if="lhxTrtcCall.callType === 'video'" @click="lhxToggleCamera" class="lhx-control-btn">📷</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 输入区域 -->
    <div class="lhx-input-container">
      <!-- LHX聊天模块 - 图片选择器（隐藏） -->
      <input 
        type="file" 
        ref="lhxImageInput" 
        @change="lhxHandleImageSelect" 
        accept="image/*" 
        style="display: none" 
      />
      
      <!-- 主输入栏 -->
      <div class="lhx-input-area">
        <!-- LHX聊天模块 - 始终显示的语音按钮 -->
        <button 
          @mousedown="lhxStartRecording"
          @mouseup="lhxStopRecording"
          @touchstart="lhxStartRecording"
          @touchend="lhxStopRecording"
          :class="['lhx-voice-btn', { 'lhx-recording': lhxVoiceRecorder.isRecording }]"
          title="长按录音"
        >
          🎤
        </button>
        
        <!-- LHX聊天模块 - 大屏直接显示的功能按钮 -->
        <div class="lhx-desktop-functions">
          <button @click="lhxSelectImage" class="lhx-image-btn" title="发送图片">
            📷
          </button>
          
          <button 
            @click="lhxStartCall('audio')"
            :disabled="lhxTrtcCall.isInCall"
            class="lhx-call-btn"
            title="音频通话"
          >
            📞
          </button>
          
          <button 
            @click="lhxStartCall('video')"
            :disabled="lhxTrtcCall.isInCall"
            class="lhx-call-btn"
            title="视频通话"
          >
            📹
          </button>
        </div>
        
        <!-- LHX聊天模块 - 输入框 -->
        <input 
          v-model="lhxInputMessage" 
          @keyup.enter="lhxSendMessage"
          placeholder="输入消息..."
          class="lhx-message-input"
        />
        
        <!-- LHX聊天模块 - 发送按钮 -->
        <button 
          @click="lhxSendMessage"
          :disabled="!lhxInputMessage.trim()"
          class="lhx-send-btn"
          title="发送消息"
        >
          <span class="lhx-send-icon">⬆</span>
          <span class="lhx-send-text">发送</span>
        </button>
        
        <!-- LHX聊天模块 - 小屏展开/收起按钮 -->
        <button 
          @click="lhxToggleMoreFunctions"
          class="lhx-toggle-btn"
          title="更多功能"
        >
          {{ lhxShowMoreFunctions ? '×' : '+' }}
        </button>
      </div>
      
      <!-- LHX聊天模块 - 微信样式的底部功能面板 -->
      <Transition name="lhx-panel">
        <div v-show="lhxShowMoreFunctions" class="lhx-function-panel">
          <div class="lhx-function-grid">
            <button @click="lhxSelectImage" class="lhx-function-item" title="发送图片">
              <div class="lhx-function-icon">📷</div>
              <span class="lhx-function-label">相册</span>
            </button>
            
            <button 
              @click="lhxStartCall('audio')"
              :disabled="lhxTrtcCall.isInCall"
              class="lhx-function-item"
              title="音频通话"
            >
              <div class="lhx-function-icon">📞</div>
              <span class="lhx-function-label">语音通话</span>
            </button>
            
            <button 
              @click="lhxStartCall('video')"
              :disabled="lhxTrtcCall.isInCall"
              class="lhx-function-item"
              title="视频通话"
            >
              <div class="lhx-function-icon">📹</div>
              <span class="lhx-function-label">视频通话</span>
            </button>
            
            <!-- 可以继续添加更多功能 -->
            <button class="lhx-function-item" title="更多功能">
              <div class="lhx-function-icon">⚙️</div>
              <span class="lhx-function-label">更多</span>
            </button>
          </div>
        </div>
      </Transition>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { io, Socket } from 'socket.io-client';

// 动态导入非关键模块，避免阻塞首屏（暂时注释，按需启用）
// let TRTC: any = null;
// const loadTRTC = async () => {
//   if (!TRTC) {
//     TRTC = (await import('trtc-js-sdk')).default;
//   }
//   return TRTC;
// };

// 临时保持原有导入方式，避免破坏现有功能
import TRTC from 'trtc-js-sdk';

const route = useRoute();
const router = useRouter();

// 从路由参数获取聊天信息
const lhxRoomId = ref(route.query.lhxRoomId as string || '');
const lhxCurrentUser = ref({
  userId: route.query.lhxUserId as string || '',
  userType: route.query.lhxUserType as string || '',
  name: route.query.lhxUserName as string || ''
});


const lhxOtherUserName = ref((route.query.lhxDoctorName || route.query.lhxPatientName) as string || '');

// 判断当前用户类型
const lhxIsPatient = computed(() => lhxCurrentUser.value.userType === 'patient');



// Socket和消息相关
const lhxSocket = ref<Socket | null>(null);
const lhxSocketConnected = ref(false);
const lhxConnecting = ref(false);
const lhxMessages = ref<any[]>([]);
const lhxInputMessage = ref('');
const lhxMessagesContainer = ref<HTMLElement | null>(null);

// LHX聊天模块 - 功能按钮展开/收纳状态管理
const lhxShowMoreFunctions = ref((() => {
  // 从localStorage读取用户偏好，默认收起
  try {
    const saved = localStorage.getItem('lhx_show_more_functions');
    return saved ? JSON.parse(saved) : false;
  } catch {
    return false;
  }
})());

// 分页懒加载相关状态 - 性能优化
const lhxPagination = ref({
  currentPage: 1,
  pageSize: 20,
  hasMore: true,
  loading: false,
  initialLoaded: false,
  enabled: false // 新增：条件启用分页
});

// 消息缓存相关
const lhxMessageCache = ref({
  oldestMessageId: '',
  newestMessageId: '',
  totalCount: 0
});

// 计算属性：是否启用分页功能
const lhxShouldUsePagination = computed(() => {
  // 只有在消息数量较多或已明确需要分页时才启用
  return lhxPagination.value.enabled || lhxMessages.value.length > 50;
});

// 清理函数
onUnmounted(() => {
  if (lhxSocket.value) {
    lhxSocket.value.disconnect();
  }
});

// LHX聊天模块 - 图片功能相关
const lhxImageInput = ref<HTMLInputElement | null>(null);

// LHX聊天模块 - 图片预览相关
const lhxImagePreview = ref({
  show: false,
  url: '',
  alt: ''
});

// LHX聊天模块 - 语音录制相关
const lhxVoiceRecorder = ref({
  isRecording: false,
  mediaRecorder: null as MediaRecorder | null,
  audioChunks: [] as Blob[],
  startTime: 0,
  duration: 0
});

// LHX聊天模块 - 语音播放相关
const lhxVoicePlayer = ref({
  currentPlaying: null as string | null,
  audio: null as HTMLAudioElement | null
});

// LHX聊天模块 - TRTC音视频通话相关
const lhxTrtcCall = ref({
  isInCall: false,
  callType: '' as 'audio' | 'video' | '',
  isIncoming: false,
  remoteUserId: '',
  trtcRoomId: 0,
  client: null as any,
  localStream: null as any,
  remoteStream: null as any
});






/**
 * 获取头像URL
 */
function lhxGetAvatarUrl(userId?: string) {
  if (!userId) return '/default-avatar.png';
  
  // 根据用户ID或类型返回对应头像
  if (userId.startsWith('d')) return '/default-doctor.png';
  if (userId.startsWith('p')) return '/default-patient.png';
  return '/default-avatar.png';
}

/**
 * 格式化消息时间
 */
function lhxFormatMessageTime(timestamp: string | Date) {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const now = new Date();
  const isToday = date.toDateString() === now.toDateString();
  
  if (isToday) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }
}

/**
 * 滚动到底部
 */
async function lhxScrollToBottom() {
  await nextTick();
  if (lhxMessagesContainer.value) {
    lhxMessagesContainer.value.scrollTop = lhxMessagesContainer.value.scrollHeight;
  }
}

/**
 * 滚动事件处理：检测上拉加载（条件启用）
 */
function lhxHandleScroll() {
  // 只有启用分页功能时才处理滚动加载
  if (!lhxShouldUsePagination.value || !lhxMessagesContainer.value || 
      !lhxPagination.value.hasMore || lhxPagination.value.loading) {
    return;
  }
  
  const { scrollTop } = lhxMessagesContainer.value;
  
  // 滚动到顶部附近时触发加载更多
  const threshold = 100; // 距离顶部100px时开始加载
  if (scrollTop <= threshold) {
    console.log('LHX: 触发上拉加载更多消息');
    lhxLoadMoreMessages();
  }
}

/**
 * 连接Socket
 */
function lhxConnectSocket() {
  if (lhxSocket.value) return;
  
  lhxConnecting.value = true;
  console.log('LHX: 连接Socket到 http://localhost:3000');
  
  lhxSocket.value = io('http://localhost:3000', {
    transports: ['websocket', 'polling']
  });
  
  // 连接成功
  lhxSocket.value.on('connect', () => {
    console.log('LHX: Socket连接成功');
    lhxSocketConnected.value = true;
    lhxConnecting.value = false;
    lhxJoinRoom();
  });
  
  // 连接失败
  lhxSocket.value.on('connect_error', (error) => {
    console.error('LHX: Socket连接失败', error);
    lhxSocketConnected.value = false;
    lhxConnecting.value = false;
  });
  
  // 断开连接
  lhxSocket.value.on('disconnect', () => {
    console.log('LHX: Socket连接断开');
    lhxSocketConnected.value = false;
  });
  
  // 接收历史消息
  lhxSocket.value.on('lhx_history_messages', (data) => {
    console.log('LHX: 收到历史消息', data);
    
    // 检查是否需要启用分页功能
    if (!lhxPagination.value.enabled && data.totalCount > 50) {
      lhxPagination.value.enabled = true;
      console.log('LHX: 启用分页功能，总消息数:', data.totalCount);
    }
    
    lhxHandleHistoryMessages(data);
  });
  
  // 接收新消息
  lhxSocket.value.on('lhx_receive_message', (message) => {
    console.log('LHX: 收到新消息', message);
    lhxMessages.value.push(message);
    
    // 更新最新消息ID
    lhxMessageCache.value.newestMessageId = message._id;
    lhxMessageCache.value.totalCount++;
    
    lhxScrollToBottom();
  });
  

  
  // 错误处理
  lhxSocket.value.on('lhx_error', (error) => {
    console.error('LHX: Socket错误', error);
    alert(`聊天错误: ${error.message}`);
  });

  // LHX聊天模块 - 通话信令监听
  lhxSocket.value.on('lhx_call_invitation', (data) => {
    console.log('LHX: 收到通话邀请', data);
    lhxTrtcCall.value.isIncoming = true;
    lhxTrtcCall.value.callType = data.callType;
    lhxTrtcCall.value.trtcRoomId = data.trtcRoomId;
    lhxTrtcCall.value.remoteUserId = data.fromUserId;
  });

  lhxSocket.value.on('lhx_call_accepted', (data) => {
    console.log('LHX: 通话被接受', data);
  });

  lhxSocket.value.on('lhx_call_rejected', (data) => {
    console.log('LHX: 通话被拒绝', data);
    alert('对方拒绝了通话');
    lhxCleanupTrtc();
    lhxResetCallState();
  });

  lhxSocket.value.on('lhx_call_cancelled', (data) => {
    console.log('LHX: 通话被取消', data);
    lhxResetCallState();
  });

  lhxSocket.value.on('lhx_call_ended', (data) => {
    console.log('LHX: 通话结束', data);
    lhxCleanupTrtc();
    lhxResetCallState();
  });
}

/**
 * 加入聊天房间
 */
function lhxJoinRoom() {
  if (!lhxSocket.value || !lhxRoomId.value) return;
  
  const [patientId, doctorId] = lhxRoomId.value.split('_');
  
  const joinData = {
    patientId,
    doctorId,
    userType: lhxCurrentUser.value.userType,
    userId: lhxCurrentUser.value.userId
  };
  
  console.log('LHX: 加入房间', joinData);
  lhxSocket.value.emit('lhx_join_room', joinData);
  
  // 加入房间后立即请求最新消息
  lhxLoadInitialMessages();
}

/**
 * 处理历史消息响应
 */
function lhxHandleHistoryMessages(data: any) {
  const { messages = [], page, hasMore, totalCount } = data;
  
  if (page === 1) {
    // 首次加载：替换消息列表
    lhxMessages.value = messages;
    lhxPagination.value.initialLoaded = true;
    if (messages.length > 0) {
      lhxMessageCache.value.newestMessageId = messages[messages.length - 1]._id;
      lhxMessageCache.value.oldestMessageId = messages[0]._id;
    }
    lhxScrollToBottom();
  } else {
    // 分页加载：在前面插入旧消息，保持滚动位置
    lhxInsertOlderMessages(messages);
  }
  
  lhxPagination.value.hasMore = hasMore;
  lhxPagination.value.loading = false;
  lhxMessageCache.value.totalCount = totalCount || 0;
  
  console.log(`LHX: 加载第${page}页消息，共${messages.length}条，还有更多: ${hasMore}`);
}

/**
 * 插入更早的消息并保持滚动位置
 */
function lhxInsertOlderMessages(messages: any[]) {
  if (!lhxMessagesContainer.value || messages.length === 0) return;
  
  const container = lhxMessagesContainer.value;
  const oldScrollHeight = container.scrollHeight;
  const oldScrollTop = container.scrollTop;
  
  // 插入消息
  lhxMessages.value = [...messages, ...lhxMessages.value];
  lhxMessageCache.value.oldestMessageId = messages[0]._id;
  
  // 使用双重nextTick确保DOM完全更新
  nextTick(() => {
    nextTick(() => {
      if (container) {
        const newScrollHeight = container.scrollHeight;
        const heightDiff = newScrollHeight - oldScrollHeight;
        
        // 精确保持滚动位置
        container.scrollTop = oldScrollTop + heightDiff;
        
        console.log(`LHX: 插入${messages.length}条历史消息，滚动位置从${oldScrollTop}调整到${container.scrollTop}`);
      }
    });
  });
}

/**
 * 加载初始消息（智能判断是否使用分页）
 */
function lhxLoadInitialMessages() {
  if (!lhxSocket.value) return;
  
  lhxPagination.value.loading = true;
  lhxPagination.value.currentPage = 1;
  
  // 首次加载时使用较大的页面大小，如果消息不多则一次性加载完
  const initialLimit = lhxPagination.value.enabled ? lhxPagination.value.pageSize : 100;
  
  lhxSocket.value.emit('lhx_load_history', {
    page: 1,
    limit: initialLimit
  });
}

/**
 * 加载更多历史消息
 */
function lhxLoadMoreMessages() {
  if (!lhxSocket.value || !lhxPagination.value.hasMore || lhxPagination.value.loading) {
    return;
  }
  
  lhxPagination.value.loading = true;
  lhxPagination.value.currentPage++;
  
  lhxSocket.value.emit('lhx_load_history', {
    page: lhxPagination.value.currentPage,
    limit: lhxPagination.value.pageSize,
    beforeMessageId: lhxMessageCache.value.oldestMessageId
  });
}



/**
 * 发送消息
 */
function lhxSendMessage() {
  if (!lhxInputMessage.value.trim()) return;
  
  const messageData = {
    content: lhxInputMessage.value.trim(),
    messageType: 'text'
  };
  
  console.log('LHX: 发送消息', messageData);
  lhxSocket.value?.emit('lhx_send_message', messageData);
  
  lhxInputMessage.value = '';
  
  // LHX聊天模块 - 发送消息后自动收起功能按钮（提升用户体验）
  if (lhxShowMoreFunctions.value) {
    lhxShowMoreFunctions.value = false;
    // 保存自动收起状态
    try {
      localStorage.setItem('lhx_show_more_functions', 'false');
    } catch (error) {
      console.warn('LHX: 无法保存功能按钮状态', error);
    }
  }
}

/**
 * LHX聊天模块 - 切换功能按钮展开/收纳状态
 */
function lhxToggleMoreFunctions() {
  lhxShowMoreFunctions.value = !lhxShowMoreFunctions.value;
  
  // 保存用户偏好到localStorage
  try {
    localStorage.setItem('lhx_show_more_functions', JSON.stringify(lhxShowMoreFunctions.value));
  } catch (error) {
    console.warn('LHX: 无法保存功能按钮状态偏好', error);
  }
  
  console.log('LHX: 切换功能按钮状态', lhxShowMoreFunctions.value ? '展开' : '收起');
}

/**
 * LHX聊天模块 - 自动隐藏功能面板（使用功能后）
 */
function lhxAutoHidePanel() {
  if (lhxShowMoreFunctions.value) {
    lhxShowMoreFunctions.value = false;
    // 保存自动收起状态
    try {
      localStorage.setItem('lhx_show_more_functions', 'false');
    } catch (error) {
      console.warn('LHX: 无法保存功能面板状态', error);
    }
  }
}

/**
 * LHX聊天模块 - 选择图片
 */
function lhxSelectImage() {
  lhxImageInput.value?.click();
  // 使用功能后自动收起面板
  lhxAutoHidePanel();
}

/**
 * LHX聊天模块 - 处理图片选择
 */
async function lhxHandleImageSelect(event: Event) {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;
  
  // 验证文件大小
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过5MB');
    return;
  }
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    alert('只能上传图片文件');
    return;
  }
  
  const formData = new FormData();
  formData.append('image', file);
  
  try {
    console.log('[LHX-CHAT] 开始上传图片...');
    
    const response = await fetch('http://localhost:3000/lhx/upload-image', {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (result.success) {
      console.log('[LHX-CHAT] 图片上传成功:', result.imageUrl);
      lhxSendImageMessage(result.imageUrl);
    } else {
      console.error('[LHX-CHAT] 图片上传失败:', result.message);
      alert('图片上传失败：' + result.message);
    }
  } catch (error) {
    console.error('[LHX-CHAT] 图片上传异常:', error);
    alert('图片上传失败，请重试');
  }
  
  // 清空文件选择器
  if (target) target.value = '';
}

/**
 * LHX聊天模块 - 发送图片消息
 */
function lhxSendImageMessage(imageUrl: string) {
  const messageData = {
    content: '',
    messageType: 'image',
    fileInfo: {
      fileUrl: imageUrl,
      fileName: imageUrl.split('/').pop() || 'image.jpg',
      mimeType: 'image/jpeg'
    }
  };
  
  console.log('[LHX-CHAT] 发送图片消息:', messageData);
  lhxSocket.value?.emit('lhx_send_message', messageData);
}

/**
 * LHX聊天模块 - 预览图片（放大显示）
 */
function lhxPreviewImage(imageUrl: string, alt: string = '图片') {
  if (imageUrl) {
    lhxImagePreview.value = {
      show: true,
      url: imageUrl,
      alt: alt
    };
  }
}

/**
 * LHX聊天模块 - 关闭图片预览
 */
function lhxCloseImagePreview() {
  lhxImagePreview.value.show = false;
}

/**
 * LHX聊天模块 - 键盘事件处理（ESC关闭预览）
 */
function lhxHandleKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape' && lhxImagePreview.value.show) {
    lhxCloseImagePreview();
  }
}

/**
 * LHX聊天模块 - 下载图片
 */
async function lhxDownloadImage() {
  try {
    const response = await fetch(lhxImagePreview.value.url);
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `lhx-chat-image-${Date.now()}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    window.URL.revokeObjectURL(url);
    console.log('[LHX-CHAT] 图片下载成功');
  } catch (error) {
    console.error('[LHX-CHAT] 图片下载失败:', error);
    alert('图片下载失败，请稍后重试');
  }
}

/**
 * LHX聊天模块 - 图片预览加载完成
 */
function lhxImagePreviewLoaded() {
  console.log('[LHX-CHAT] 图片预览加载完成');
}

/**
 * LHX聊天模块 - 图片预览加载错误
 */
function lhxImagePreviewError() {
  console.error('[LHX-CHAT] 图片预览加载失败');
  alert('图片加载失败');
  lhxCloseImagePreview();
}

/**
 * LHX聊天模块 - 图片加载错误处理
 */
function lhxImageError(event: Event) {
  const img = event.target as HTMLImageElement;
  console.error('[LHX-CHAT] 图片加载失败:', img.src);
  img.style.display = 'none';
}

/**
 * LHX聊天模块 - 开始录音
 */
async function lhxStartRecording() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream);
    
    lhxVoiceRecorder.value.audioChunks = [];
    lhxVoiceRecorder.value.mediaRecorder = mediaRecorder;
    lhxVoiceRecorder.value.isRecording = true;
    lhxVoiceRecorder.value.startTime = Date.now();
    
    mediaRecorder.ondataavailable = (event) => {
      lhxVoiceRecorder.value.audioChunks.push(event.data);
    };
    
    mediaRecorder.onstop = () => {
      lhxHandleRecordingComplete();
    };
    
    mediaRecorder.start();
    console.log('[LHX-CHAT] 开始录音');
  } catch (error) {
    console.error('[LHX-CHAT] 录音失败:', error);
    alert('无法访问麦克风，请检查权限设置');
  }
}

/**
 * LHX聊天模块 - 停止录音
 */
function lhxStopRecording() {
  if (lhxVoiceRecorder.value.mediaRecorder && lhxVoiceRecorder.value.isRecording) {
    lhxVoiceRecorder.value.mediaRecorder.stop();
    // 停止所有音频轨道
    const stream = lhxVoiceRecorder.value.mediaRecorder.stream as MediaStream;
    stream.getTracks().forEach((track: MediaStreamTrack) => track.stop());
    lhxVoiceRecorder.value.isRecording = false;
    lhxVoiceRecorder.value.duration = (Date.now() - lhxVoiceRecorder.value.startTime) / 1000;
    console.log('[LHX-CHAT] 停止录音，时长:', lhxVoiceRecorder.value.duration + '秒');
  }
}

/**
 * LHX聊天模块 - 处理录音完成
 */
async function lhxHandleRecordingComplete() {
  const audioBlob = new Blob(lhxVoiceRecorder.value.audioChunks, { type: 'audio/webm' });
  
  // 检查录音时长
  if (lhxVoiceRecorder.value.duration < 1) {
    alert('录音时间太短，请重新录制');
    return;
  }
  
  try {
    // 上传语音文件
    const formData = new FormData();
    formData.append('voice', audioBlob, `voice-${Date.now()}.webm`);
    
    const response = await fetch('http://localhost:3000/lhx/upload-voice', {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (result.success) {
      console.log('[LHX-CHAT] 语音上传成功:', result.voiceUrl);
      lhxSendVoiceMessage(result.voiceUrl, lhxVoiceRecorder.value.duration, result.fileSize);
    } else {
      console.error('[LHX-CHAT] 语音上传失败:', result.message);
      alert('语音上传失败: ' + result.message);
    }
  } catch (error) {
    console.error('[LHX-CHAT] 语音上传异常:', error);
    alert('语音上传失败，请稍后重试');
  }
}

/**
 * LHX聊天模块 - 发送语音消息
 */
function lhxSendVoiceMessage(voiceUrl: string, duration: number, fileSize: number) {
  const messageData = {
    content: '',
    messageType: 'voice',
    fileInfo: {
      fileUrl: voiceUrl,
      fileName: voiceUrl.split('/').pop() || 'voice.webm',
      mimeType: 'audio/webm',
      duration: Math.round(duration * 10) / 10, // 保留1位小数
      fileSize: fileSize
    }
  };
  
  console.log('[LHX-CHAT] 发送语音消息:', messageData);
  lhxSocket.value?.emit('lhx_send_message', messageData);
}

/**
 * LHX聊天模块 - 播放语音
 */
function lhxPlayVoice(voiceUrl: string, messageId: string) {
  // 如果正在播放同一条语音，则暂停
  if (lhxVoicePlayer.value.currentPlaying === messageId) {
    lhxStopVoice();
    return;
  }
  
  // 停止当前播放的语音
  lhxStopVoice();
  
  try {
    const audio = new Audio(voiceUrl);
    lhxVoicePlayer.value.audio = audio;
    lhxVoicePlayer.value.currentPlaying = messageId;
    
    audio.onended = () => {
      lhxVoicePlayer.value.currentPlaying = null;
      lhxVoicePlayer.value.audio = null;
    };
    
    audio.onerror = () => {
      console.error('[LHX-CHAT] 语音播放失败:', voiceUrl);
      alert('语音播放失败');
      lhxStopVoice();
    };
    
    audio.play();
    console.log('[LHX-CHAT] 开始播放语音:', messageId);
  } catch (error) {
    console.error('[LHX-CHAT] 语音播放异常:', error);
    alert('语音播放失败');
  }
}

/**
 * LHX聊天模块 - 停止播放语音
 */
function lhxStopVoice() {
  if (lhxVoicePlayer.value.audio) {
    lhxVoicePlayer.value.audio.pause();
    lhxVoicePlayer.value.audio = null;
  }
  lhxVoicePlayer.value.currentPlaying = null;
}

// ==================== LHX聊天模块 - TRTC音视频通话功能 ====================

/**
 * LHX聊天模块 - 发起通话
 */
async function lhxStartCall(callType: 'audio' | 'video') {
  // 使用功能后自动收起面板
  lhxAutoHidePanel();
  
  try {
    // 获取TRTC配置
    const response = await fetch('http://localhost:3000/lhx/get-trtc-config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId: lhxCurrentUser.value.userId })
    });
    
    const result = await response.json();
    if (!result.success) {
      alert('获取通话配置失败: ' + result.message);
      return;
    }
    
    const { sdkAppId, userId, userSig, roomId } = result.data;
    
    // LHX聊天模块 - 验证roomId是否在有效范围内
    const validRoomId = typeof roomId === 'number' && roomId >= 1 && roomId <= 4294967294 ? roomId : Math.floor(Math.random() * 4294967293) + 1;
    
    console.log(`[LHX-TRTC] TRTC配置验证: 原始roomId=${roomId}, 有效roomId=${validRoomId}`);
    
    // LHX聊天模块 - 初始化音频上下文（iOS兼容性）
    lhxInitAudioContext();
    
    // 设置通话状态
    lhxTrtcCall.value.callType = callType;
    lhxTrtcCall.value.trtcRoomId = validRoomId;
    lhxTrtcCall.value.isInCall = true;
    
    // 发送通话邀请信令
    lhxSocket.value?.emit('lhx_call_invite', {
      callType: callType,
      trtcRoomId: validRoomId
    });
    
    // 初始化TRTC客户端
    await lhxInitTrtcClient(sdkAppId, userId, userSig, validRoomId, callType);
    
    console.log(`[LHX-TRTC] 发起${callType}通话成功`);
  } catch (error) {
    console.error('[LHX-TRTC] 发起通话失败:', error);
    alert('发起通话失败，请稍后重试');
    lhxResetCallState();
  }
}

/**
 * LHX聊天模块 - 接受通话
 */
async function lhxAcceptCall() {
  try {
    // 获取TRTC配置
    const response = await fetch('http://localhost:3000/lhx/get-trtc-config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ 
        userId: lhxCurrentUser.value.userId,
        roomId: lhxTrtcCall.value.trtcRoomId
      })
    });
    
    const result = await response.json();
    if (!result.success) {
      alert('获取通话配置失败: ' + result.message);
      return;
    }
    
    const { sdkAppId, userId, userSig } = result.data;
    
    // LHX聊天模块 - 初始化音频上下文（iOS兼容性）
    lhxInitAudioContext();
    
    // 发送接受通话信令
    lhxSocket.value?.emit('lhx_call_accept', {
      trtcRoomId: lhxTrtcCall.value.trtcRoomId
    });
    
    // 更新状态
    lhxTrtcCall.value.isIncoming = false;
    lhxTrtcCall.value.isInCall = true;
    
    // 初始化TRTC客户端
    await lhxInitTrtcClient(sdkAppId, userId, userSig, lhxTrtcCall.value.trtcRoomId, lhxTrtcCall.value.callType);
    
    console.log('[LHX-TRTC] 接受通话成功');
  } catch (error) {
    console.error('[LHX-TRTC] 接受通话失败:', error);
    alert('接受通话失败');
    lhxResetCallState();
  }
}

/**
 * LHX聊天模块 - 拒绝通话
 */
function lhxRejectCall() {
  lhxSocket.value?.emit('lhx_call_reject', {
    trtcRoomId: lhxTrtcCall.value.trtcRoomId,
    reason: 'rejected'
  });
  lhxResetCallState();
}

/**
 * LHX聊天模块 - 结束通话
 */
function lhxEndCall() {
  lhxSocket.value?.emit('lhx_call_end', {
    trtcRoomId: lhxTrtcCall.value.trtcRoomId,
    duration: 0
  });
  lhxCleanupTrtc();
  lhxResetCallState();
}

/**
 * LHX聊天模块 - 初始化音频上下文（iOS兼容性）
 */
function lhxInitAudioContext() {
  try {
    // iOS Safari音频兼容性处理
    if (/iPhone|iPad/.test(navigator.userAgent)) {
      const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
      if (AudioContext) {
        const audioContext = new AudioContext();
        if (audioContext.state === 'suspended') {
          audioContext.resume().then(() => {
            console.log('[LHX-TRTC] iOS音频上下文已激活');
          }).catch((error) => {
            console.warn('[LHX-TRTC] iOS音频上下文激活失败:', error);
          });
        }
      }
    }
  } catch (error) {
    console.warn('[LHX-TRTC] 音频上下文初始化失败:', error);
  }
}

/**
 * LHX聊天模块 - 初始化TRTC客户端
 */
async function lhxInitTrtcClient(sdkAppId: number, userId: string, userSig: string, roomId: number, callType: string) {
  try {
    // 创建TRTC客户端
    const client = TRTC.createClient({
      mode: 'rtc',
      sdkAppId: sdkAppId,
      userId: userId,
      userSig: userSig
    });
    
    lhxTrtcCall.value.client = client;
    
    // 监听远端流
    client.on('stream-added', (event: any) => {
      const remoteStream = event.stream;
      console.log('[LHX-TRTC] 远端流加入:', remoteStream.getId());
      client.subscribe(remoteStream);
    });
    
    client.on('stream-subscribed', (event: any) => {
      const remoteStream = event.stream;
      lhxTrtcCall.value.remoteStream = remoteStream;
      
      // LHX聊天模块 - 根据通话类型指定播放容器（TRTC自动创建audio/video元素）
      if (callType === 'video') {
        remoteStream.play('lhx-remote-video');
      } else {
        remoteStream.play('lhx-remote-audio'); // 语音通话使用div容器，TRTC自动创建audio元素
      }
      console.log('[LHX-TRTC] 远端流订阅成功, 播放容器:', callType === 'video' ? 'video' : 'audio');
    });
    
    // 加入房间
    await client.join({ roomId: roomId });
    console.log('[LHX-TRTC] 加入房间成功');
    
    // 创建本地流
    const localStream = TRTC.createStream({
      userId: userId,
      audio: true,
      video: callType === 'video'
    });
    
    await localStream.initialize();
    lhxTrtcCall.value.localStream = localStream;
    
    // LHX聊天模块 - 根据通话类型播放本地流（TRTC自动创建audio/video元素）
    if (callType === 'video') {
      localStream.play('lhx-local-video');
    } else {
      localStream.play('lhx-local-audio'); // 语音通话使用div容器，TRTC自动创建audio元素
    }
    
    // 发布本地流
    await client.publish(localStream);
    console.log('[LHX-TRTC] 本地流发布成功, 播放容器:', callType === 'video' ? 'video' : 'audio');
    
  } catch (error) {
    console.error('[LHX-TRTC] TRTC客户端初始化失败:', error);
    throw error;
  }
}

/**
 * LHX聊天模块 - 清理TRTC资源
 */
function lhxCleanupTrtc() {
  if (lhxTrtcCall.value.client) {
    lhxTrtcCall.value.client.leave();
    lhxTrtcCall.value.client = null;
  }
  if (lhxTrtcCall.value.localStream) {
    lhxTrtcCall.value.localStream.close();
    lhxTrtcCall.value.localStream = null;
  }
  lhxTrtcCall.value.remoteStream = null;
}

/**
 * LHX聊天模块 - 重置通话状态
 */
function lhxResetCallState() {
  lhxTrtcCall.value.isInCall = false;
  lhxTrtcCall.value.isIncoming = false;
  lhxTrtcCall.value.callType = '';
  lhxTrtcCall.value.remoteUserId = '';
  lhxTrtcCall.value.trtcRoomId = 0;
}

/**
 * LHX聊天模块 - 切换静音
 */
function lhxToggleMute() {
  if (lhxTrtcCall.value.localStream) {
    const audioTrack = lhxTrtcCall.value.localStream.getAudioTrack();
    if (audioTrack) {
      audioTrack.enabled = !audioTrack.enabled;
    }
  }
}

/**
 * LHX聊天模块 - 切换摄像头
 */
function lhxToggleCamera() {
  if (lhxTrtcCall.value.localStream) {
    const videoTrack = lhxTrtcCall.value.localStream.getVideoTrack();
    if (videoTrack) {
      videoTrack.enabled = !videoTrack.enabled;
    }
  }
}



/**
 * 返回上一页
 */
function lhxGoBack() {
  router.back();
}

/**
 * 断开Socket连接
 */
function lhxDisconnectSocket() {
  if (lhxSocket.value) {
    lhxSocket.value.disconnect();
    lhxSocket.value = null;
  }
  lhxSocketConnected.value = false;
}

// 监听消息变化，自动滚动到底部（防抖优化）
watch(() => lhxMessages.value.length, () => {
  // 只有在消息列表不为空且已经初始化完成时才滚动
  if (lhxMessages.value.length > 0 && lhxPagination.value.initialLoaded) {
    lhxScrollToBottom();
  }
}, { 
  flush: 'post' // 在DOM更新后执行
});

// 组件挂载 - 优化首屏性能
onMounted(() => {
  console.log('LHX: 聊天窗口挂载', {
    roomId: lhxRoomId.value,
    currentUser: lhxCurrentUser.value,
    otherUser: lhxOtherUserName.value
  });
  
  if (!lhxRoomId.value || !lhxCurrentUser.value.userId) {
    alert('聊天参数不完整，请重新进入');
    router.back();
    return;
  }
  
  // 优化：延迟Socket连接，不阻塞首屏渲染
  nextTick(() => {
    // 使用requestIdleCallback或setTimeout确保首屏渲染完成
    if (window.requestIdleCallback) {
      window.requestIdleCallback(() => lhxConnectSocket());
    } else {
      setTimeout(() => lhxConnectSocket(), 0);
    }
  });
  
  // LHX聊天模块 - 添加键盘事件监听
  document.addEventListener('keydown', lhxHandleKeydown);
});

// 组件卸载
onUnmounted(() => {
  console.log('LHX: 聊天窗口卸载');
  lhxDisconnectSocket();
  
  // LHX聊天模块 - 清理TRTC资源
  lhxCleanupTrtc();
  
  // LHX聊天模块 - 移除键盘事件监听
  document.removeEventListener('keydown', lhxHandleKeydown);
});
</script>

<style scoped>
.lhx-chat-window {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f8f9fa;
  /* CSS保护 - 防止整体容器溢出 */
  overflow-x: hidden; /* 防止水平滚动 */
  max-width: 100vw; /* 不超过视口宽度 */
  box-sizing: border-box;
}

.lhx-chat-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.lhx-back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  margin-right: 12px;
  padding: 8px;
  border-radius: 4px;
  color: #3498db;
}

.lhx-back-btn:hover {
  background: #f0f0f0;
}

.lhx-chat-title h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.lhx-chat-with {
  margin: 4px 0 0 0;
  color: #666;
  font-size: 14px;
}

.lhx-connection-status {
  padding: 8px 0;
  background: #f39c12;
  color: white;
  text-align: center;
  font-size: 14px;
}

.lhx-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f8f9fa;
  min-height: 400px; /* 固定最小高度，减少CLS */
  contain: layout style paint; /* CSS containment优化性能 */
  /* CSS保护 - 防止消息区域溢出 */
  overflow-x: hidden; /* 防止水平滚动 */
  max-width: 100%; /* 不超过容器宽度 */
  box-sizing: border-box;
}

.lhx-empty-messages {
  text-align: center;
  padding: 40px;
  color: #666;
}

.lhx-empty-messages small {
  display: block;
  margin-top: 8px;
  color: #999;
}

/* LHX聊天模块 - Skeleton Screen样式 */
.lhx-skeleton-container {
  padding: 16px;
}

.lhx-skeleton-message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
  gap: 12px;
}

.lhx-skeleton-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: lhx-skeleton-shimmer 2s infinite;
}

.lhx-skeleton-content {
  flex: 1;
}

.lhx-skeleton-text {
  height: 16px;
  border-radius: 4px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: lhx-skeleton-shimmer 2s infinite;
  margin-bottom: 8px;
}

.lhx-skeleton-text.short {
  width: 60%;
}

.lhx-skeleton-text.long {
  width: 85%;
}

@keyframes lhx-skeleton-shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

/* 简化的加载提示 */
.lhx-loading-more-simple {
  text-align: center;
  padding: 8px;
  color: #999;
  font-size: 18px;
  letter-spacing: 2px;
}

.lhx-message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
  gap: 22px;
}



.lhx-message-avatar {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
  margin-top: 0;
}

.lhx-message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background: #e0e0e0;
}

.lhx-message-content {
  max-width: 70%;
  margin-top: 0;
}

.lhx-message.lhx-self .lhx-message-content {
  text-align: right;
  align-self: flex-end;
  margin-left: auto;
}

.lhx-message-bubble {
  display: inline-block;
  padding: 12px 16px;
  border-radius: 18px;
  max-width: 100%;
  word-wrap: break-word;
  line-height: 1.4;
}

.lhx-message.lhx-self .lhx-message-bubble {
  background: #3498db;
  color: white;
}

.lhx-message.lhx-other .lhx-message-bubble {
  background: white;
  color: #333;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.lhx-message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.lhx-typing-indicator {
  margin-bottom: 16px;
}

.lhx-typing-bubble {
  background: white;
  padding: 12px 16px;
  border-radius: 18px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.lhx-typing-dots {
  display: flex;
  gap: 2px;
}

.lhx-typing-dots span {
  width: 6px;
  height: 6px;
  background: #999;
  border-radius: 50%;
  animation: lhx-typing-animation 1.5s infinite;
}

.lhx-typing-dots span:nth-child(2) {
  animation-delay: 0.3s;
}

.lhx-typing-dots span:nth-child(3) {
  animation-delay: 0.6s;
}

@keyframes lhx-typing-animation {
  0%, 60%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  30% {
    opacity: 1;
    transform: scale(1);
  }
}

/* LHX聊天模块 - 输入容器（包含输入栏和功能面板） */
.lhx-input-container {
  background: white;
  border-top: 1px solid #eee;
  /* CSS保护 - 防止输入容器溢出 */
  overflow-x: hidden;
  max-width: 100%;
  box-sizing: border-box;
}

/* LHX聊天模块 - 主输入栏 */
.lhx-input-area {
  display: flex;
  padding: 12px 16px;
  gap: 8px;
  align-items: flex-end;
  flex-wrap: nowrap; /* 防止换行 */
  overflow-x: hidden; /* 防止水平溢出 */
  max-width: 100%; /* 确保不超出容器 */
  box-sizing: border-box; /* 包含padding在内的宽度计算 */
}

.lhx-message-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 16px; /* 防止iOS自动缩放 */
  min-height: 44px; /* 移动端最小触摸目标 */
  max-height: 100px;
  resize: none;
  line-height: 1.4;
  /* CSS保护 - 防止输入框溢出 */
  min-width: 0; /* 允许flex收缩到最小 */
  box-sizing: border-box; /* 包含padding和border */
  overflow-wrap: break-word; /* 长单词自动换行 */
  word-break: break-word; /* 强制换行 */
}

.lhx-message-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 1px rgba(52, 152, 219, 0.2);
}

.lhx-message-input:disabled {
  background: #f5f5f5;
  color: #999;
}

.lhx-send-btn {
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: background-color 0.2s;
  min-width: 44px; /* 移动端最小触摸目标 */
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  /* CSS保护 - 防止文字换行和按钮变形 */
  white-space: nowrap;
  flex-shrink: 0; /* 不允许收缩 */
  overflow: hidden; /* 防止内容溢出 */
}

.lhx-send-btn:active:not(:disabled) {
  background: #2980b9;
}

.lhx-send-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

/* LHX聊天模块 - 发送按钮图标样式 */
.lhx-send-icon {
  font-size: 16px;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* LHX聊天模块 - 发送按钮文字样式 */
.lhx-send-text {
  font-size: 14px;
  font-weight: 600;
  line-height: 1;
}

/* LHX聊天模块 - 响应式发送按钮 */
/* 小屏幕（<400px）：只显示图标，节省空间 */
@media (max-width: 399px) {
  .lhx-send-text {
    display: none; /* 隐藏文字 */
  }
  
  .lhx-send-btn {
    min-width: 44px;
    width: 44px; /* 固定为圆形按钮 */
    padding: 8px;
  }
  
  .lhx-send-icon {
    font-size: 18px; /* 稍微放大图标 */
  }
}

/* 中等屏幕（400px-479px）：显示图标+文字 */
@media (min-width: 400px) and (max-width: 479px) {
  .lhx-send-btn {
    min-width: max-content; /* 根据内容确定宽度 */
  }
}

/* 大屏幕（≥480px）：显示图标+文字，更宽松的布局 */
@media (min-width: 480px) {
  .lhx-send-btn {
    padding: 10px 20px;
    min-width: max-content;
  }
  
  .lhx-send-text {
    font-size: 15px; /* 大屏幕稍大的文字 */
  }
}

/* LHX聊天模块 - 桌面端功能按钮容器 */
.lhx-desktop-functions {
  display: none; /* 小屏默认隐藏 */
  gap: 8px;
  align-items: center;
  /* CSS保护 - 防止按钮组溢出 */
  flex-shrink: 0; /* 不允许收缩 */
  overflow: hidden; /* 防止内容溢出 */
}

/* LHX聊天模块 - 展开/收起切换按钮 */
.lhx-toggle-btn {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  cursor: pointer;
  font-size: 20px;
  font-weight: normal;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  /* CSS保护 - 防止按钮变形 */
  flex-shrink: 0; /* 不允许收缩 */
  min-width: 44px;
  min-height: 44px;
}

.lhx-toggle-btn:active {
  background: #e8e8e8;
  transform: scale(0.95);
}

/* LHX聊天模块 - 微信样式的功能面板 */
.lhx-function-panel {
  padding: 16px;
  padding-bottom: max(16px, env(safe-area-inset-bottom)); /* 适配底部安全区域 */
  background: #f7f7f7;
  border-top: 1px solid #e5e5e5;
}

.lhx-function-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  max-width: 320px;
  margin: 0 auto;
}

.lhx-function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 8px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.2s;
  min-height: 80px;
}

.lhx-function-item:active {
  background: rgba(0, 0, 0, 0.05);
}

.lhx-function-item:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.lhx-function-icon {
  font-size: 32px;
  margin-bottom: 8px;
  line-height: 1;
}

.lhx-function-label {
  font-size: 12px;
  color: #666;
  text-align: center;
  line-height: 1.2;
}

/* LHX聊天模块 - 响应式断点系统 */

/* 超小屏幕 (320px以下) - 极简布局 */
@media (max-width: 319px) {
  .lhx-input-area {
    gap: 4px; /* 减小间距 */
    padding: 8px 12px; /* 减小内边距 */
  }
  
  .lhx-voice-btn,
  .lhx-send-btn,
  .lhx-toggle-btn {
    width: 36px;
    height: 36px;
    min-width: 36px;
    min-height: 36px;
    font-size: 14px;
  }
  
  .lhx-message-input {
    font-size: 14px;
    padding: 8px 12px;
    min-height: 36px;
  }
  
  .lhx-send-btn {
    padding: 8px 12px;
    font-size: 12px;
  }
}

/* 小屏幕 (320px - 374px) - 紧凑布局 */
@media (min-width: 320px) and (max-width: 374px) {
  .lhx-input-area {
    gap: 6px;
    padding: 10px 14px;
  }
  
  .lhx-voice-btn,
  .lhx-send-btn,
  .lhx-toggle-btn {
    width: 40px;
    height: 40px;
    min-width: 40px;
    min-height: 40px;
    font-size: 16px;
  }
  
  .lhx-message-input {
    font-size: 15px;
    padding: 10px 14px;
    min-height: 40px;
  }
  
  .lhx-send-btn {
    padding: 10px 16px;
    font-size: 13px;
  }
}

/* 中小屏幕 (375px - 413px) - iPhone SE/8 等 */
@media (min-width: 375px) and (max-width: 413px) {
  .lhx-input-area {
    gap: 8px;
    padding: 12px 16px;
  }
  
  .lhx-message-content {
    max-width: 75%; /* 稍微增加消息宽度 */
  }
}

/* 中屏幕 (414px - 479px) - iPhone Plus/Max 等 */
@media (min-width: 414px) and (max-width: 479px) {
  .lhx-input-area {
    gap: 8px;
    padding: 12px 16px;
  }
  
  .lhx-message-content {
    max-width: 80%; /* 进一步增加消息宽度 */
  }
  
  /* 在这个尺寸开始显示部分桌面功能，但保持紧凑 */
  .lhx-desktop-functions {
    display: none; /* 仍然隐藏，避免过于拥挤 */
  }
}

/* 大屏幕 (480px - 767px) - 小平板/横屏手机 */
@media (min-width: 480px) and (max-width: 767px) {
  .lhx-desktop-functions {
    display: flex; /* 显示桌面功能按钮 */
    gap: 6px; /* 紧凑间距 */
  }
  
  .lhx-toggle-btn {
    display: none; /* 隐藏切换按钮 */
  }
  
  .lhx-function-panel {
    display: none; /* 隐藏功能面板 */
  }
  
  .lhx-message-content {
    max-width: 65%; /* 平板上消息不要太宽 */
  }
  
  .lhx-input-area {
    gap: 8px;
    padding: 12px 20px;
  }
}

/* 大平板 (768px - 1023px) */
@media (min-width: 768px) and (max-width: 1023px) {
  .lhx-desktop-functions {
    display: flex;
    gap: 8px;
  }
  
  .lhx-toggle-btn {
    display: none;
  }
  
  .lhx-function-panel {
    display: none;
  }
  
  .lhx-message-content {
    max-width: 60%; /* 平板上进一步限制宽度 */
  }
  
  .lhx-input-area {
    gap: 10px;
    padding: 16px 24px;
  }
  
  .lhx-messages {
    padding: 20px 24px;
  }
}

/* 桌面端 (1024px以上) */
@media (min-width: 1024px) {
  .lhx-desktop-functions {
    display: flex;
    gap: 10px;
  }
  
  .lhx-toggle-btn {
    display: none;
  }
  
  .lhx-function-panel {
    display: none;
  }
  
  .lhx-message-content {
    max-width: 55%; /* 桌面端消息宽度更窄，便于阅读 */
  }
  
  .lhx-input-area {
    gap: 12px;
    padding: 16px 32px;
  }
  
  .lhx-messages {
    padding: 24px 32px;
  }
  
  .lhx-chat-window {
    max-width: 800px; /* 限制整体最大宽度 */
    margin: 0 auto;
  }
}

/* LHX聊天模块 - 全局防溢出保护 */
.lhx-chat-window img,
.lhx-chat-window video,
.lhx-chat-window canvas {
  max-width: 100%; /* 防止媒体内容溢出 */
  height: auto;
  box-sizing: border-box;
}

/* 长文本处理 */
.lhx-message-bubble,
.lhx-message-content {
  overflow-wrap: break-word;
  word-break: break-word;
  hyphens: auto; /* 自动断词 */
}

/* 防止固定定位元素造成的溢出 */
.lhx-call-overlay,
.lhx-function-panel {
  max-width: 100vw;
  box-sizing: border-box;
}

/* LHX聊天模块 - 功能按钮统一样式 */
.lhx-image-btn {
  padding: 10px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  color: #3498db;
  border-radius: 50%;
  transition: background-color 0.2s;
  min-width: 44px; /* 移动端最小触摸目标 */
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lhx-image-btn:active {
  background: #f0f0f0;
}

/* LHX聊天模块 - 录音按钮样式 */
.lhx-voice-btn {
  width: 44px; /* 移动端最小触摸目标 */
  height: 44px;
  border: none;
  border-radius: 50%;
  background: #f5f5f5;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  user-select: none;
  /* CSS保护 - 防止按钮变形 */
  flex-shrink: 0; /* 不允许收缩 */
  min-width: 44px;
  min-height: 44px;
}

.lhx-voice-btn:active {
  background: #f0f0f0;
}

.lhx-voice-btn.lhx-recording {
  background: #e74c3c;
  color: white;
  animation: lhx-recording-pulse 1s infinite;
}

@keyframes lhx-recording-pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

/* LHX聊天模块 - 功能面板滑入/滑出动画效果 */
.lhx-panel-enter-active,
.lhx-panel-leave-active {
  transition: all 0.3s ease;
  transform-origin: center top;
}

.lhx-panel-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}

.lhx-panel-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

/* LHX聊天模块 - 通话按钮样式 */
.lhx-call-btn {
  width: 44px; /* 移动端最小触摸目标 */
  height: 44px;
  border: none;
  border-radius: 50%;
  background: #27ae60;
  color: white;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.lhx-call-btn:active:not(:disabled) {
  background: #219a52;
}

.lhx-call-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

/* LHX聊天模块 - 图片消息样式 */
.lhx-image-message {
  max-width: 100%;
}

.lhx-image-message img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  display: block;
  transition: transform 0.2s ease;
  object-fit: cover;
  border: none; /* LHX聊天模块 - 去除图片边框 */
  outline: none;
}

.lhx-image-message img:hover {
  transform: scale(1.02);
}

/* LHX聊天模块 - 语音消息样式 */
.lhx-voice-message {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 120px;
}

.lhx-voice-play-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 50%;
  background: #3498db;
  color: white;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.lhx-voice-play-btn:hover {
  background: #2980b9;
}

.lhx-voice-play-btn.lhx-playing {
  background: #e74c3c;
}

.lhx-voice-duration {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* LHX聊天模块 - 图片放大预览样式 */
.lhx-image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(4px);
}

.lhx-image-preview-container {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.lhx-image-preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.lhx-image-preview-close {
  background: none;
  border: none;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  color: #666;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.lhx-image-preview-close:hover {
  background: #e9ecef;
  color: #333;
}

.lhx-image-preview-download {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.lhx-image-preview-download:hover {
  background: #2980b9;
}

.lhx-image-preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  min-height: 200px;
}

.lhx-image-preview-content img {
  max-width: 100%;
  max-height: 70vh;
  border-radius: 8px;
  object-fit: contain;
  border: none;
  outline: none;
}

/* LHX聊天模块 - 通话弹窗样式 */
.lhx-call-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

.lhx-call-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  text-align: center;
}

.lhx-call-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 20px;
}

.lhx-call-info p {
  margin: 0 0 24px 0;
  color: #666;
  font-size: 16px;
}

.lhx-call-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.lhx-accept-btn {
  background: #27ae60;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s;
}

.lhx-accept-btn:hover {
  background: #219a52;
}

.lhx-reject-btn {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s;
}

.lhx-reject-btn:hover {
  background: #c0392b;
}

.lhx-video-container {
  position: relative;
  margin: 20px 0;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.lhx-remote-video {
  width: 100%;
  height: 200px;
  background: #000;
}

.lhx-local-video {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 80px;
  height: 60px;
  background: #333;
  border-radius: 4px;
  border: 2px solid white;
}

.lhx-audio-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 12px;
  min-height: 120px;
}

.lhx-audio-info {
  text-align: center;
}

.lhx-audio-icon {
  font-size: 48px;
  margin-bottom: 16px;
  animation: lhx-audio-pulse 2s infinite;
}

.lhx-audio-info p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

@keyframes lhx-audio-pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.7; }
  100% { transform: scale(1); opacity: 1; }
}

.lhx-call-controls {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 20px;
}

.lhx-control-btn {
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 50%;
  background: #34495e;
  color: white;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.lhx-control-btn:hover {
  background: #2c3e50;
}

.lhx-end-call-btn {
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 50%;
  background: #e74c3c;
  color: white;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.lhx-end-call-btn:hover {
  background: #c0392b;
}
</style>